/*日期格式化*/
import {
  HttpRequest,
  get,
  post
} from "./httpRequest";

let CryptoJS = require("crypto-js");

function dtFormat(timestamp: number, format: string, obj = { isResObj: false }): (string | object) {
  const SECOND = 1 * 1000;
  const MINUTE = 1 * 60 * SECOND;
  const HOURS = 1 * 60 * MINUTE;
  const DAY = 1 * 24 * HOURS;
  let dateType = 'dd|d|hh|h|mm|m|ss|s';
  let formatArr = (format || '').match(new RegExp(dateType + '|.', 'g')) || [];
  let dateTimeObj = {
    day: 0,
    hour: 0,
    minute: 0,
    second: 0
  };
  let dateTimeStr = '';
  let day: number, hour: number, minute: number, second: number;
  if (/dd|d/.test(format)) {
    //存在天
    day = timestamp > DAY ? Math.floor(timestamp / DAY) : 0;
    hour = (timestamp - day * DAY) >= HOURS ? Math.floor((timestamp - day * DAY) / HOURS) : 0;
    minute = (timestamp - day * DAY - hour * HOURS) >= MINUTE ? Math.floor((timestamp - day * DAY - hour *
      HOURS) / MINUTE) : 0;
    second = Math.round((timestamp - day * DAY - hour * HOURS - minute * MINUTE) / 1000);
  } else if (/hh|h/.test(format)) {
    hour = timestamp >= HOURS ? Math.floor(timestamp / HOURS) : 0;
    minute = (timestamp - hour * HOURS) >= MINUTE ? Math.floor((timestamp - hour * HOURS) / MINUTE) : 0;
    second = Math.round((timestamp - hour * HOURS - minute * MINUTE) / 1000);
  } else if (/mm|m/.test(format)) {
    minute = timestamp >= MINUTE ? Math.floor(timestamp / MINUTE) : 0;
    second = Math.round((timestamp - minute * MINUTE) / 1000);
  } else if (/ss|s/.test(format)) {
    second = Math.round(timestamp / 1000);
  }
  formatArr.forEach((item) => {
    if (new RegExp(dateType).test(item)) {
      if (/dd|d/.test(item)) { //天
        dateTimeStr += item.length == 2 ? (day < 10 ? '0' + day : day) : day;
        dateTimeObj.day = day
      } else if (/hh|h/.test(item)) { //时
        dateTimeStr += item.length == 2 ? (hour < 10 ? '0' + hour : hour) : hour;
        dateTimeObj.hour = hour
      } else if (/mm|m/.test(item)) { //分
        dateTimeStr += item.length == 2 ? (minute < 10 ? '0' + minute : minute) : minute;
        dateTimeObj.minute = minute;
      } else if (/ss|s/.test(item)) { //秒
        dateTimeStr += item.length == 2 ? (second < 10 ? '0' + second : second) : second;
        dateTimeObj.second = second;
      }
    } else {
      dateTimeStr += item
    }
  })
  // console.log(dateTimeStr);
  return obj.isResObj ? dateTimeObj : dateTimeStr;
}

//本地存储-设置
function setStorage(key: string, data: any) {
  return new Promise((resolve) => {
    let storage = getStorage(key);
    if (storage && Object.prototype.toString.call(data) === '[object Object]') {
      for (var k in data) {
        storage[k] = data[k]
      }
    } else {
      storage = data;
    }
    wx.setStorageSync(key, storage);
    resolve(storage);
  })
}
//本地存储-删除
function removeStorage(key: string) {
  return new Promise<void>((resolve, reject) => {
    try {
      wx.removeStorageSync(key)
      resolve();
    } catch (e) {
      reject();
    }
  })
}
//本地存储-获取
function getStorage(key: string) {
  let storage;
  try {
    const value = wx.getStorageSync(key)
    if (value) {
      storage = value;
    }
    return storage;
  } catch (e) {
    console.warn("getStorage-fail:" + key);
  }
}

/**
 * @description:设置环境
 * @val {number} 1-测试  2-formal 3-正式 
 * @return {*}
 */
function setEnvConfig(val: number) {
  let ckPluginEnvConfig = {
    sdkAppId: 0,
    env: 3,
    apiUrl: ""
  }
  switch (val * 1) {
    case 1:
      ckPluginEnvConfig.env = 1;
      ckPluginEnvConfig.sdkAppId = 1400339505;
      ckPluginEnvConfig.apiUrl = 'https://kpapi-cs.ckjr001.com/api/';
      break;
    case 2:
      ckPluginEnvConfig.env = 2;
      ckPluginEnvConfig.sdkAppId = 1400488765;
      ckPluginEnvConfig.apiUrl = 'https://formalapi.ckjr001.com/api/';
      break;
    case 3:
      ckPluginEnvConfig.env = 3;
      ckPluginEnvConfig.sdkAppId = 1400488765;
      ckPluginEnvConfig.apiUrl = 'https://kpapiop.ckjr001.com/api/';
      break
    default:
      ckPluginEnvConfig.env = 3;
      ckPluginEnvConfig.sdkAppId = 1400488765;
      ckPluginEnvConfig.apiUrl = 'https://kpapiop.ckjr001.com/api/';
  }
  wx.setStorageSync('envConfig', ckPluginEnvConfig);
}


function getRoles(role: (number | string), subRole: (number | string)) {
  let res = {
    isTeacher: false,
    isAdmin: false,
    isGuest: false,
    isNormal: false
  };
  if (role == 2) {
    if (subRole == 1) {
      res.isGuest = true;
    } else {
      res.isTeacher = true;
    }
  } else if (role == 4) {
    res.isAdmin = true;
  } else if (role == 6) {
    res.isAdmin = true;
    if (subRole == 1) {
      res.isGuest = true;
    } else {
      res.isTeacher = true;
    }
  } else {
    res.isNormal = true;
  }
  // console.log("_getRoles", res);
  return res;
}

function decrypt(str: string, key: string, iv: string) {
  let res = str;
  let aesKey = '';
  let aesVi = '';
  let companyShare = getStorage("companyShare");
  if (CryptoJS) {
    aesKey = key || companyShare.passKey.key;
    aesVi = iv || companyShare.passKey.vi;
    if (aesKey && aesVi) {
      key = CryptoJS.enc.Utf8.parse(aesKey);
      iv = CryptoJS.enc.Utf8.parse(aesVi);
      let decrypted = CryptoJS.AES.decrypt(str, key, { iv: iv, padding: CryptoJS.pad.Pkcs7 });
      res = decrypted.toString(CryptoJS.enc.Utf8);
    }
  }
  return res;
}

/**
   * @description:获取dynamicName（依赖注入）
   * @param {Array} teacherAndAdminKey  讲师和管理员的jiguangUserName集合
   */
function getDynamicName(data: any, roles: any, isShowRealName: boolean) {
  if (Object.prototype.toString.call(data) == '[object Object]') {
    if (roles.isAdmin || roles.isTeacher) {
      if (isShowRealName) {
        data.dynamicName = data.userRealName || data.realName || data.userName;
      } else {
        data.dynamicName = data.realName || data.userName;
      }
    } else {
      data.dynamicName = data.realName || data.userName;
    }
  }
  return data;
}

function getHideName(name: string, hiddenLiveUserName = false) {
  if (!hiddenLiveUserName) {
    return name;
  }
  if (name) {
    name = name.toString().replace(/^(.{3})(.+)/, '$1***')
  }
  return name;
}
/**
   * @description:获取dynamicName（依赖注入）
   * @data {object} {filePath:文件路劲,nameKey:"文件对应的 key",ispInfo:{网络服务提供商相关信息},nameCreate:生成文件的名称}
   */
function upload(data: any) {
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: data.ispInfo.host, //仅为示例，非真实的接口地址
      filePath: data.filePath,
      name: data.nameKey || 'file',
      formData: {
        'name': data.nameCreate,
        'key': data.ispInfo.dir + data.nameCreate,
        'policy': data.ispInfo.policy,
        'OSSAccessKeyId': data.ispInfo.accessid,
        'success_action_status': '200',
        'callback': data.ispInfo.callback,
        'signature': data.ispInfo.signature,
      },
      success: (res) => {
        if (res.statusCode == 200) {
          let resData = JSON.parse(res.data);
          resolve(resData.data.url);
        } else {
          reject();
          wx.showToast({
            title: "上传失败",
            icon: "none"
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: "上传失败",
          icon: "none"
        })
        reject();
      },
      complete: () => {

      }
    })
  })
}

function uuid() {
  let s: any = [];
  let hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  // s[8] = s[13] = s[18] = s[23] = "-";

  var uuid = s.join("");
  return uuid;
}

function indexOf(arr: any, value: any) {
  if (arr.indexOf(value) < 0) {
    return false;
  } else {
    return true;
  }
}

function split(sourceStr: any, char: any) {
  let str = '' + sourceStr;
  return str.split(char)
}

// function includes(arr = [], item:(number | string)){
//   return arr.includes(item);
// }


function relacetTime(timestr: (number | string)) {
  var str = '' + timestr;
  str = str.replace(RegExp('-', 'g'), '.').split(' ')[0];
  return str;
}

function replace(str: string, regex: string, val: string) {
  return ('' + str).replace(regex, val)
}

function formatAudioTime(num: any) {
  num = num * 1;
  var min = Math.floor(num / 60);
  var second = Math.floor(num % 60);
  var res = "";
  if (min) {
    res = min + "'"
  }
  if (second) {
    res = res + second + "''"
  }
  return res;
}


function getBindPhoneSetting(ckFrom: (string | number)) {
  return new Promise((resolve, reject) => {
    let bindPhoneSetting = {
      buyBind: false, // 购买前
      passwordBind: false, // 输入密码前
      getBind: false, // 获得前
      helpBind: false, // 助力前
      enrollBind: false, // 报名/投票前
      commentBind: false, // 评论前
      isVisitorBind: false, //游客模式需要绑定手机号的功能，（这个是对不需要绑定手机号的功能游客模式下绑定）
      shareBind: false, //邀请、分享前
      collectBind: false, //点赞、收藏、关注前
      rewardBind: false, //打赏前
      isHadPhone: false
    };
    let companyShare = getStorage("companyShare");
    console.log("companyShare", companyShare.userMobile)
    if (companyShare.userMobile) {
      bindPhoneSetting.isHadPhone = true;
      resolve(bindPhoneSetting);
    } else {
      get(`company/bindPhoneInstall`, {
        prodType: ckFrom
      }).then(res => {
        if (res && res.length > 0) {
          res.forEach(item => {
            if(item.type == 1 && item.enableBind){
              bindPhoneSetting.buyBind = true;
            } else if(item.type == 2 && item.enableBind){
              bindPhoneSetting.passwordBind = true;
            } else if(item.type == 3 && item.enableBind){
              bindPhoneSetting.getBind = true;
            } else if(item.type == 4 && item.enableBind){
              bindPhoneSetting.helpBind = true;
            } else if(item.type == 5 && item.enableBind){
              bindPhoneSetting.enrollBind = true;
            } else if(item.type == 6 && item.enableBind){
              bindPhoneSetting.commentBind = true;
            } else if(item.type == 7 && item.enableBind){
              bindPhoneSetting.shareBind = true;
            } else if(item.type == 8 && item.enableBind){
              bindPhoneSetting.collectBind = true;
            } else if(item.type == 9 && item.enableBind){
              bindPhoneSetting.rewardBind = true;
            }
          });
        }
        bindPhoneSetting.isHadPhone = false;
        console.log("bindPhoneSetting", bindPhoneSetting);
        resolve(bindPhoneSetting);
        return bindPhoneSetting;
      }).catch(() => {
        resolve({});
        return {}
      })
    }
  })
}


let requestAniFrame = (function () {
  if (typeof window !== 'undefined') {
    return (
      window.requestAnimationFrame ||
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      function (callback) {
        window.setTimeout(callback, 1000 / 60);
      }
    );
  } else {
    return function (callback: Function) {
      setTimeout(callback, 1000 / 60);
    };
  }
}())

function isIos() {
  let systemInfo = getStorage("systemInfo");
  return systemInfo.platform == 'ios' || systemInfo.platform == 'mac' || /ios/.test(systemInfo.system.toLowerCase())
}

function getTimeByDate(dateStr: any) {
  if (dateStr != '' && dateStr != null && dateStr != undefined) {
    let time = 0;
    let timeHead = dateStr.split(" ")[0].split("-");
    let timeEnd = dateStr.split(" ")[1].split(":");
    let date = new Date(timeHead[0], (parseInt(timeHead[1]) - 1), timeHead[2], timeEnd[0], timeEnd[1], timeEnd[2]);
    time = date.getTime();
    return time;
  } else {
    return 0;
  }
}

function navigateToGuide(data: any = {}) {
  let envConfig = getStorage("envConfig");
  let roomToken = getStorage("roomToken");
  let params: any = {}
  params = {
    roomToken: roomToken,
    env: envConfig.env,
    socialRoomId: data.socialRoomId,
    ...data
  }
  wx.navigateTo({
    url: '/pages/commerce-guide/index',
    success: (res) => {
      res.eventChannel.emit('acceptDataFromOpenerPage', params)
    }
  });
}


// function toFixed(num,len){
//   return Number(num).toFixed(len)
// }


function toFixed(num: any, s: any): string {
  var times = Math.pow(10, s)
  var des = num * times + 0.5
  return parseInt(des + '', 10) / times + '';
}


export default {
  indexOf: indexOf,
  split: split,
  replace: replace,
  // includes: includes,
  relacetTime: relacetTime,
  formatAudioTime: formatAudioTime,
  dtFormat,
  setStorage,
  removeStorage,
  getStorage,
  setEnvConfig,
  HttpRequest,
  get,
  post,
  getRoles,
  decrypt,
  getDynamicName,
  getHideName,
  upload,
  uuid,
  getBindPhoneSetting,
  isIos: isIos,
  navigateToGuide: navigateToGuide,
  toFixed: toFixed,
  getTimeByDate: getTimeByDate,
  requestAniFrame: requestAniFrame,
}
